<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	
	    <base href="<%=basePath%>">
	    
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">    
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<link rel="stylesheet" type="text/css" href="<%=basePath%>/easyui/themes/default/easyui.css" />
		<link rel="stylesheet" type="text/css" href="<%=basePath%>/easyui/themes/icon.css" />
		<link rel="stylesheet" type="text/css" href="<%=basePath%>/css/index.css" />
		<title>index Page</title>
	
	</head>

	<body>
		<table id="role"></table>
		
		<div id="role_tool" style="padding:5px;">
			<div style="margin-bottom:5px;">
				<a href="#" class="easyui-linkbutton" iconCls="icon-add-new" plain="true" onclick="role_tool.add();">添加</a>
				<a href="#" class="easyui-linkbutton" iconCls="icon-edit-new" plain="true" onclick="role_tool.edit();">修改</a>
				<a href="#" class="easyui-linkbutton" iconCls="icon-delete-new" plain="true" onclick="role_tool.remove();">删除</a>
				<a href="#" class="easyui-linkbutton" iconCls="icon-reload" plain="true"  onclick="role_tool.reload();">刷新</a>
				<a href="#" class="easyui-linkbutton" iconCls="icon-redo" plain="true" onclick="role_tool.redo();">取消选择</a>	
			</div>
			
			<div style="padding:0 0 0 7px;color:#333;">
				 搜索：
				<div id="search"></div>
				<div id="pox">
					<div name="roleIdSearch" data-options="iconCls:'icon-id'">查询编号</div>
					<div name="roleNameSearch" data-options="iconCls:'icon-user'">查询名称</div>
				</div>
			</div>
		</div>
		
		<form id="role_add" style="margin:0;padding:5px 0 0 25px;color:#333;">
			<p>角色名称：<input type="text" name="roleName" class="textbox" style="width:200px;"></p>
			<p>角色备注：<input type="text" name="roleRemark" class="textbox" style="width:200px;"></p>
			<p>分配权限：<input id="auth" class="textbox" name="auth" style="width:205px;"></p>
		</form>
		
		<form id="role_edit" style="margin:0;padding:5px 0 0 25px;color:#333;">
			<input type="hidden" name="roleId_edit" class="textbox" style="width:200px;">
			<p><input type="hidden" name="isDelete" class="textbox" style="width:200px;"></p>
			<p>角色名称：<input type="text" name="roleName_edit" class="textbox" style="width:200px;"></p>
			<p>角色备注：<input type="text" id="roleRemark_edit" name="roleRemark_edit" class="textbox" style="width:200px;"></p>
			<p>分配权限：<input id="auth_edit" class="textbox" name="auth_edit" style="width:205px;"></p>
		</form>
		<script type="text/javascript" src="<%=basePath%>/easyui/jquery.min.js"></script>
		<script type="text/javascript" src="<%=basePath%>/easyui/jquery.easyui.min.js"></script>
		<script type="text/javascript" src="<%=basePath%>/easyui/locale/easyui-lang-zh_CN.js" ></script>
		<script type="text/javascript" >
			$.extend($.fn.validatebox.defaults.rules, {
				roleNameRepetition : {
				     validator: function (value) {
				    	 var b = "0";
				    	 $.ajax({
				    	        type: "post",
				    	        dataType: "text",
				    	        async: false,
				    	        data :{
				    	        	name : value
				    	        },
				    	        url: "roleAction!isExistRole",
				    	        success: function (data) {
				    	        	if(data > 0){
				    	        		b = "1";
				    	        	}
				    	        }
				    	    });
			                return (b=="1") ? true : false;
			         },
			    	message: '角色名已被占用' 
				},
			    equalTo: { 
			    	validator: function (value, param) { 
			    		return $(param[0]).val() == value;
			    	 }, 
			    	message: '两次输入的密码不一致' 
			    }
			 });
			
			$(function () {
					
				$('#role').datagrid({
					url : 'roleAction!getRoleList',
					fit : true,
					fitColumns : true,
					striped : true,
					rownumbers : true,
					border : false,
					pagination : true,
					pageSize : 10,
					pageList : [5, 10, 15, 20, 25],
					pageNumber : 1,
					sortName : 'roleId',
					sortOrder : 'asc',
					toolbar : '#role_tool',
					remoteSort:	false,
				    frozenColumns:[[
				    ]], 
					columns : [[
				    	{
				    		field:"ck",	
				    		align:'center',
				    		checkbox:true,	
				    		title : '自动编号',
				    		width:100
				    	},    
						{
							field : 'roleId',
							align:'center',
							title : '角色编号',
							width : 100,
							sortable : true
						},	
						{
							field : 'roleName',
							align:'center',
							title : '角色名称',
							width : 100,
							sortable : true
						},
						{
							field : 'roleRemark',
							align:'center',
							title : '角色描述',
							width : 100,
							sortable : true
						}
					]]
				});
					
				$('#role_add').dialog({
					width : 350,
					title : '新增角色',
					modal : true,
					closed : true,
					iconCls : 'icon-add-new',
					buttons : [{
						text : '提交',
						iconCls : 'icon-add-new',
						handler : function () {
							if ($('#role_add').form('validate')) {
								$.ajax({
									url : 'roleAction!addRole',
									type : 'post',
									data : {
										roleName : $('input[name="roleName"]').val(),
										roleRemark : $('input[name="roleRemark"]').val(),
										authIds : function (){
											var ids = $('#auth').combotree('getValues');
											return ids.join(',');
										}
									},
									beforeSend : function () {
										$.messager.progress({
											text : '正在新增中...'
										});
									},
									success : function (data, response, status) {
										$.messager.progress('close');
										
										if (data > 0) {
											$.messager.show({
												title : '提示',
												msg : '新增角色成功！！！'
											});
											$('#role_add').dialog('close').form('reset');
											$('#role').datagrid('reload');
										} else {
											$.messager.alert('新增失败！', '未知错误导致失败，请重试！', 'warning');
										}
									}
								});
							}
						}
					},{
						text : '取消',
						iconCls : 'icon-redo',
						handler : function () {
							$('#role_add').dialog('close').form('reset');
						}
					}]
				});
				
				//新增管理帐号
				$('input[name="roleName"]').validatebox({
					required : true,
					validType : [
				         'length[2,20]',
				         'roleNameRepetition'
					],
					missingMessage : '请输入管理名称'
					//invalidMessage : '管理名称在 2-20 位',
				});
				
				//新增分配权限
				$('#auth').combotree({
					url: "treeAction!syncMenu?type=all&date="+new Date()+"",
					required : true,
					lines : true,
					multiple : true,
					checkbox : true,
					cascadeCheck: false,
			        onCheck: function (node, checked) {
			          if (checked) {
			        	var tree_ = $("#auth").combotree('tree');
			            var parentNode = tree_.tree('getParent', node.target);
			            if (parentNode != null) {
			            	tree_.tree('check', parentNode.target);
			            } 
			          } else {
			        	var tree_ = $("#auth").combotree('tree');
			            var childNode = tree_.tree('getChildren', node.target);
			            if (childNode.length > 0) {
			              for (var i = 0; i < childNode.length; i++) {
			            	  tree_.tree('uncheck', childNode[i].target);
			              }
			            }
			          }
			        }
				});
				
				
				//修改
				$('#role_edit').dialog({
					width : 350,
					title : '修改角色',
					modal : true,
					closed : true,
					iconCls : 'icon-edit-add',
					buttons : [{
						text : '提交',
						iconCls : 'icon-edit-new',
						handler : function () {
							if ($('#manager_edit').form('validate')) {
								$.ajax({
										url : 'roleAction!updateRole',
										type : 'post',
										data : {
											isDelete : $('input[name="isDelete"]').val(),
										    roleId : $('input[name="roleId_edit"]').val(),
											roleName : $('input[name="roleName_edit"]').val(),
											roleRemark : $('input[name="roleRemark_edit"]').val(),
											authIds : function(){
												//console.log($('#auth_edit').combotree('getValues'));
												var ids = $('#auth_edit').combotree('getValues');
												return ids.join(',');
											}
										},
										beforeSend : function () {
											$.messager.progress({
												text : '正在修改中...'
											});
										},
										success : function (data, response, status) {
											
											$.messager.progress('close');
											if (data > 0) {
												$.messager.show({
													title : '提示',
													msg : '修改角色成功'
												});
												$('#role_edit').dialog('close').form('reset');
												$('#role').datagrid('reload');
												parent.$('#nav').tree('reload');
											} else {
												$.messager.alert('修改失败！', '未知错误导致失败，请重试！', 'warning');
											}
										}
									});
							}
						}
					},{
						text : '取消',
						iconCls : 'icon-redo',
						handler : function () {
							$('#role_edit').dialog('close').form('reset');
						}
					}]
				});
				
				//修改角色名称
				$('input[name="roleName_edit"]').validatebox({
					required : true,
					validType : 'length[2,20]',
					missingMessage : '请输入角色名称',
					invalidMessage : '管理名称在 2-20 位',
				});
				
				//修改分配权限
				$('#auth_edit').combotree({
					url : "treeAction!syncMenu?type=all&date="+new Date()+"",
					required : true,
					lines : true,
					multiple : true,
					checkbox : true,
					cascadeCheck: false,
			        onCheck: function (node, checked) {
			          if (checked) {
			        	var tree_ = $("#auth_edit").combotree('tree');
			            var parentNode = tree_.tree('getParent', node.target);
			            if (parentNode != null) {
			            	tree_.tree('check', parentNode.target);
			            } 
			          } else {
			        	var tree_ = $("#auth_edit").combotree('tree');
			            var childNode = tree_.tree('getChildren', node.target);
			            if (childNode.length > 0) {
			              for (var i = 0; i < childNode.length; i++) {
			            	  tree_.tree('uncheck', childNode[i].target);
			              }
			            }
			          }
			        }
				});
				
				//按钮事件
				role_tool = {
					//刷新
					reload : function () {
						$('#role').datagrid('reload');
					},
					//撤销
					redo : function () {
						$('#role').datagrid('unselectAll');
						$('#search').form('clear');
					},
					//添加
					add : function () {
						$('#role_add').dialog('open');
						$('input[name="roleName"]').focus();
					},
					//删除
					remove : function () {
						var rows = $('#role').datagrid('getSelections');
						if (rows.length > 0) {
							$.messager.confirm('确定操作', '您正在要删除所选的记录吗？', function (flag) {
								if (flag) {
									var roleIds = [];
									for (var i = 0; i < rows.length; i ++) {
										roleIds.push(rows[i].roleId);
									}
									$.ajax({
										type : 'POST',
										url : 'roleAction!deleteRole',
										data : {
											roleIds : roleIds.join(',')
										},
										beforeSend : function () {
											$('#role').datagrid('loading');
											$.messager.progress({
												text : '正在删除中...'
											});
										},
										success : function (data, response, status) {
											$.messager.progress('close');
											var obj = $.parseJSON(data);
											$('#role').datagrid('loaded');
											$('#role').datagrid('load');
											$('#role').datagrid('unselectAll');
											if(obj.type > 0){
												$.messager.show({
													title : '提示',
													msg : obj.message
												});
											} else{
												$.messager.alert(obj.result, obj.message, 'warning');
											}
										}
									});
								}
							});
						} else {
							$.messager.alert('提示', '请选择要删除的记录！', 'info');
						}
					},
					//编辑
					edit : function () {
							var menuIdString;
							var rows = $('#role').datagrid('getSelections');
							if (rows.length > 1) {
								$.messager.alert('警告操作！', '编辑记录只能选定一条数据！', 'warning');
							} else if (rows.length == 1) {
								
								$.ajax({
									url : 'roleAction!getRoleByRoleId',
									type : 'post',
									data : {
										roleId : rows[0].roleId
									},
									beforeSend : function () {
										$.messager.progress({
											text : '正在获取中...'
										});
									},
									success : function (data, response, status) {
										$.messager.progress('close');
										if (data) {
											var obj = $.parseJSON(data);
											$('#role_edit').form('load', {
												isDelete : obj.role.isDelete,
												roleId_edit : obj.role.roleId,
												roleName_edit : obj.role.roleName,
												roleRemark_edit : obj.role.roleRemark
											}).dialog('open');
											$('#auth_edit').combotree('setValues',obj.menuIds);
										} else {
											$.messager.alert('获取失败！', '未知错误导致失败，请重试！', 'warning');
										}
									}
								});
							} else if (rows.length == 0) {
								$.messager.alert('警告操作！', '编辑记录至少选定一条数据！', 'warning');
							}
						}
					};
				
				//搜索栏
				$('#search').searchbox({
					width : 300,
					height : 22,
					menu : '#pox',
					searcher : function (value,column) {
						$('#role').datagrid('load', {
							column : column,
							value : value
						});
					},
					prompt : '请输入关键字'
				});
			});
		</script>
	</body>
</html>
